package main;

import java.util.concurrent.*;

/**
 * @author Xu,
 * @data 2020/11/24，
 * @time 12:30
 * 2线程处理
 * 正数作为一个子线程计算并加到结果pi中
 * 负数作为一个子线程计算并加到结果pi
 */
public class DoubleThread {
    private double sf = 1.0;
    private double pi = 0.0;
    private double item = 1.0;
    private double den = 1.0;
    private double sf1 = -1.0;
    private double item1 = -1/3.0;
    private double den1 = 3.0;
    private double pi1 = 0.0;
    private final double MAX = 1e-10;

    public DoubleThread(){
        long start = System.currentTimeMillis();
        /**
         * 线程池真是难啃。
         */
        ExecutorService executorService = new ThreadPoolExecutor(2, 2, 0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                        while (Math.abs(item) >= MAX) {
                            pi += item;
                            den += 4;
                            item = sf / den;
                        }
                }
            });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                while (Math.abs(item1) >= MAX) {
                    pi1 += item1;
                    den1 += 4;
                    item1 = sf1 / den1;
                }
            }
        });
        executorService.shutdown();
        while(!executorService.isTerminated()){ }
         pi = 4*(pi+pi1);
        //System.out.println("pi的值为: "+ pi);
        long end = System.currentTimeMillis();
        System.out.println("runtime: " + (end - start)/1000.0+"s");
    }
}
